// 创建用户typ
import { defineStore } from "pinia"
import { reqLogin, reqUserInfo, reqUserlogout } from "@/api/user/index" //登陆接口方法
import type { loginfrom, LoginReturn, userdata, LogOut } from "@/api/user/type" //引入输入账号密码类型检测ts
import { userstate } from "./types/type"
import {
  SETTOKEN,
  GETTOKEN,
  SETUSERNAME,
  GETUSERNAME,
  SETIMG,
  GETIMG,
  SETtime,
  GETtime,
} from "@/utils/token"
import { broadcast } from "@/router/router"

let useCounterStore = defineStore("user", {
  state: (): userstate => {
    //存数据
    return {
      token: GETTOKEN(),
      //localStorage.getItem("token"), //用的时候取出来这样pinia中存储的token就是持久化的
      menurouter: broadcast, //路由数据表达
      // 路由数据存储在pinia
      username: GETUSERNAME(),
      avatar: GETIMG(),
    }
  },
  actions: {
    //处理异步以及逻辑 登陆获取token
    async LogService(data: loginfrom) {
      // 处理用户登陆
      const { code, data: res, message }: any = await reqLogin(data)

      if (code === 200) {
        //存储token
        SETTOKEN(<string>res)
        let timestamp = Date.now()
        // console.log(timestamp,);

        SETtime(<number>timestamp)
        // localStorage.setItem("token", (<string>res.token)) //类型断言token是字符串存进去
        this.token = res as string //是字符串的情况下在赋值给token
        return "ok"
      } else {
        return Promise.reject(new Error(message))
      }
    },
    async userinof() {
      const { code, data }: any = await reqUserInfo()
      if (code === 200) {
        SETUSERNAME(data.name as string)
        this.username = data.name
        SETIMG(data.avatar as string)
        this.avatar = data.avatar
        // return "获取用户信息成功"
      } // else {
      // return Promise.reject('获取用户信息失败')
      // }
    },
    async Clearuser() {
      ////清除用户数据token等
      const { code, message }: any = await reqUserlogout()
      if (code === 200) {
        ;(this.username = ""),
          (this.avatar = ""),
          (this.token = ""),
          localStorage.removeItem("token")
        localStorage.removeItem("username")
        localStorage.removeItem("avatar")
        localStorage.removeItem("time")
        return "ok"
      } else {
        return Promise.reject(new Error(message))
      }
    },
  },
  getters: {},
})
// 导出这个实例
export default useCounterStore
